from rest_framework.viewsets import ModelViewSet
from cmdb.models import Idc,ServerGroup,Server
from cmdb.serializers import IdcSerializer,ServerGroupSerializer,ServerSerializer
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.views import APIView
from system_config.models import Credential
from libs.ssh import SSH

class IdcViewSet(ModelViewSet):
    queryset = Idc.objects.all()  # 指定操作的数据
    serializer_class = IdcSerializer  # 指定序列化器
    filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend]  # 指定过滤器
    search_fields = ('name', )  # 指定可搜索的字段
    filter_fields = ('city',)   # 指定过滤的字段

class ServerGroupViewSet(ModelViewSet):
    queryset = ServerGroup.objects.all()  # 指定操作的数据
    serializer_class = ServerGroupSerializer  # 指定序列化器
    filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend]  # 指定过滤器
    search_fields = ('name', )  # 指定可搜索的字段
    filter_fields = ('name',)   # 指定过滤的字段

class ServerViewSet(ModelViewSet):
    queryset = Server.objects.all()  # 指定操作的数据
    serializer_class = ServerSerializer  # 指定序列化器
    filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend]  # 指定过滤器
    search_fields = ('name','hostname','public_ip', 'private_ip' )  # 指定可搜索的字段
    filter_fields = ('idc', 'server_group',)   # 指定过滤的字段

class HostCollectView(APIView):
    def get(self, request):
        hostname = request.query_params.get('hostname')
        # ssh_ip = request.query_params.get('ssh_ip')
        # ssh_port = request.query_params.get('ssh_port')

        server = Server.objects.get(hostname=hostname)
        ssh_ip = server.ssh_ip
        ssh_port = server.ssh_port
        credential_id = server.credential.id

        credential = Credential.objects.get(id=credential_id)
        username = credential.username
        if credential.auth_mode == 1:
            password = credential.password
            ssh = SSH(ssh_ip, ssh_port, username, password=password)
        else:
            private_key = credential.private_key # key的内容，并不是一个文件
            ssh = SSH(ssh_ip, ssh_port, username, key=private_key)

        result = ssh.command('ls -l')
        print(result)
